// pages/ai/ai.js
const app_id = "117041779"
const secret_key = "OQZ3AE1jeoCnlb7Hu711feBQAeXF2E5e"
const api_key = "PxlsR3mBdrs9zYtZoBiN8ygJ"
Page({

  /**
   * 页面的初始数据
   */
  data: {
    data_duihua:"",
    access_token:""


  },
  //在小程序中调用后端接口获取access token
  getAccessToken(){
    let that = this
    wx.request({
      url: 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=' + api_key + '&client_secret=' + secret_key,
      method:'POST',
      'header':{
        'Content-Type':'application/json',
        'Accept':'application/json'
      },
      success:(res)=>{
        that.setData({
          access_token:res.data.access_token
        })
        that.instructModel()
      },
      fail:(err)=>{
        reject(err);
      }
    });
  },
  instructModel(){

    let that = this
    const access_token = that.data.access_token
    const url_chat = `https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions?access_token=${access_token}`;
    const payload = {
      "messages":[
        {
          "role":"user",
          "content":that.data.neirong//问的问题
        }
      ]
    };
    wx.showLoading({
      title: '生成中...',
    });
    wx.request({
      url: url_chat,
      method:"POST",
      data:payload,
      header:{
        'Content-Type':'application/json'
      },
      success:function(res){
        console.log(res.data);
        that.setData({
          data_duihua:res.data.result
        })
        wx.hideLoading();
      },
    });
  },
  bindKeyInput(e){
    let that = this
    console.log(e.detail.value);
    that.setData({
      neirong:e.detail.value
    })
  },
  ok(){
    this.getAccessToken()
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})